/**
 * 添加用户 编辑用户
 * @author xiaoxujs
 */

import { FC, useCallback, useEffect, useRef, useState } from "react";
import { DrawerAddChangeBox, FormBox, FormItemBox, FormItemBoxHeight } from "./style";
import InputX from "../../../../../components/InputX";
import Tree from '../../../../../components/Tree'
import ButtonX from "../../../../../components/ButtonX";
import { TreeFZProps } from "../../../../../type/common";
import { ISyhtMenuGetMenuAllTree } from "../../../../../type/ConfigManagement/MenuPage/api";
import { postSyhtMenuGetMenuAllTree } from "../../../../../api/ConfigManagement/menuPageApi";
import { ISyhtUserGetUser } from "../../../../../type/ConfigManagement/UserPage/api";
import { getSyhtMenuGetMenuTree, getSyhtUserGetUser, postSyhtUserAddUser, postSyhtUserUpdateUser } from "../../../../../api/ConfigManagement/userPageApi";
import { ISyhtRoleGetRoleList } from "../../../../../type/ConfigManagement/RolePage/api";
import { postSyhtRoleGetRoleList } from "../../../../../api/dropDownApi";
import { SelectX } from "../../../../../components/UiManagement";
import { ISelectProps } from "../../../../../type/components";


export const DrawerAddChange: FC<{
    open: boolean, // 是否打开
    onClose: () => void, // 关闭抽屉
    userId?: string, // 用户ID 编辑角色时使用
}> = ({
    open, // 是否打开
    onClose, // 关闭抽屉
    userId
}) => {
        const DrawerBoxRef = useRef<HTMLDivElement>(null);
        const DrawerBoxContentRef = useRef<HTMLDivElement>(null);
        const [treeData, setTreeData] = useState<TreeFZProps[]>([]); // 树状结构数据
        const [selectIdArr, setSelectIdArr] = useState<string[]>([]); // 选中的id数组
        const [userName, setUserName] = useState<string>(''); // 用户名称
        const [password, setPassword] = useState<string>(''); // 密码
        const [passwordConfirm, setPasswordConfirm] = useState<string>(''); // 确认密码
        const [roleList, setRoleList] = useState<ISelectProps[]>([]); // 角色列表
        const [userType, setUserType] = useState<string>(''); // 用户类型
        const [adminPassword, setAdminPassword] = useState<string>(''); // 管理员密码
        const treeFun = useCallback(
            async () => {
                const { code, msg, data } = await postSyhtMenuGetMenuAllTree() as { code: number, msg: string, data: ISyhtMenuGetMenuAllTree[] };
                if (code === 200) {
                    let list: TreeFZProps[] = []
                    // 遍历树形结构， 复制一个新的树形结构
                    const loop = (data: ISyhtMenuGetMenuAllTree[], arr: TreeFZProps[]) => {
                        data.forEach((item) => {
                            let tepData: TreeFZProps = {
                                title: item.menuName,
                                key: item.menuId,
                                menuType: item.menuType, // 菜单类型 0 目录 1 菜单 2 按钮
                            }
                            if (item.children && item.children.length > 0) {
                                tepData.children = [];
                                loop(item.children, tepData.children)
                            }
                            arr.push(tepData)
                        })
                    }
                    loop(data, list);
                    setTreeData(list);
                } else {
                    alert(msg)
                }
                const roleData = await postSyhtRoleGetRoleList() as { code: number, msg: string, data: ISyhtRoleGetRoleList[] };
                if (roleData.code === 200) {
                    let arr: ISelectProps[] = []
                    roleData.data.forEach(element => {
                        arr.push({
                            value: element.roleId,
                            label: element.roleName,
                        })
                    });
                    setRoleList([...arr])
                } else {
                    alert(roleData.msg)
                }
            },
            [],
        )

        useEffect(() => {

            ; (async () => {
                if (userId) {
                    const { code, msg, data } = await getSyhtUserGetUser({ userId }) as { code: number, msg: string, data: ISyhtUserGetUser };
                    if (code === 200) {
                        setUserName(data.userName); // 用户名称
                        setSelectIdArr(data.menuIdList); // 选中的id数组 
                        setUserType(data.roleId); // 用户类型
                    } else {
                        alert(msg)
                    }
                }
            })();
        }, [userId])

        useEffect(() => {
            treeFun();
        }, [treeFun])

        // 点击取消按钮
        const handleCancel = useCallback(
            () => {
                setUserName(''); // 用户名称
                setPassword(''); // 密码
                setSelectIdArr([]); // 选中的id数组
                setUserType(''); // 用户类型
                setAdminPassword(''); // 管理员密码
                setPasswordConfirm(''); // 确认密码
            },
            [],
        )

        useEffect(() => {
            let DrawerBoxRefCurrent = DrawerBoxRef.current;
            let DrawerBoxContentRefCurrent = DrawerBoxContentRef.current;
            const functionValue = (event: any) => {
                if (DrawerBoxContentRefCurrent?.contains(event.target as Node)) {

                } else {
                    handleCancel();
                    onClose();
                }
            }

            if (DrawerBoxRefCurrent && DrawerBoxContentRefCurrent) {
                DrawerBoxRefCurrent.addEventListener('click', functionValue)
            }
            return () => {
                if (DrawerBoxRefCurrent && DrawerBoxContentRefCurrent) {
                    DrawerBoxRefCurrent.removeEventListener('click', functionValue)
                }
            }
        }, [handleCancel, onClose]);

        // 点击确定按钮
        const handleSumber = async () => {
            if (adminPassword === '') {
                alert('管理员密码不能为空')
                return;
            }
            if (userName === '') {
                alert('用户名称不能为空')
                return;
            }
            if (selectIdArr.length === 0) {
                alert('请选择权限')
                return;
            }

            if (userId) {
                // 判断密码是否修改
                if (password !== '') { // 有修改
                    // 判断密码和确认密码是否一致
                    if (password !== passwordConfirm) { // 不一致
                        alert('两次密码不一致')
                        return;
                    } else {
                        const params = {
                            userId, // 用户ID
                            userName, // 用户名
                            password, // 用户密码
                            roleId: userType, // 用户类型
                            menuIdList: selectIdArr, // 菜单id列表
                            adminPassword, // 管理员密码
                        }
                        const { code, msg } = await postSyhtUserUpdateUser(params) as { code: number, msg: string };
                        if (code === 200) {
                            alert('修改成功')
                            handleCancel();
                            onClose();
                        } else {
                            alert(msg)
                        }
                    }
                } else {
                    const params = {
                        userId, // 用户ID
                        userName, // 用户名
                        roleId: userType, // 用户类型
                        menuIdList: selectIdArr, // 菜单id列表
                        adminPassword, // 管理员密码
                    }
                    const { code, msg } = await postSyhtUserUpdateUser(params) as { code: number, msg: string };
                    if (code === 200) {
                        alert('修改成功')
                        handleCancel();
                        onClose();
                    } else {
                        alert(msg)
                    }
                }
            } else {
                if (password === '') {
                    alert('密码不能为空')
                    return;
                }
                const params = {
                    userName, // 用户名
                    password, // 用户密码
                    roleId: userType, // 用户类型
                    menuIdList: selectIdArr, // 菜单id列表
                    adminPassword, // 管理员密码
                }
                const { code, msg } = await postSyhtUserAddUser(params) as { code: number, msg: string };
                if (code === 200) {
                    alert('添加成功')
                    handleCancel();
                    onClose();
                } else {
                    alert(msg)
                }
            }

        }
        //   修改用户类型
        const handleChangeUserType = async (value: ISelectProps) => {
            setUserType(value.value)
            //  选中之后做下权限回调
            const { code, msg, data } = await getSyhtMenuGetMenuTree({ roleId: value.value }) as { code: number, msg: string, data: { sysMenuRoleList: string[] } };
            if (code === 200) {
                setSelectIdArr(data.sysMenuRoleList) // 选中的id数组
            } else {
                alert(msg)
            }
        }

        return <DrawerAddChangeBox ref={DrawerBoxRef} open={open}>
            <div ref={DrawerBoxContentRef} className="drawer_content" >
                <div className="drawer_header">
                    <div className="drawer_title">添加</div>
                    <span className="guanbi" aria-hidden="true" onClick={() => {
                        handleCancel()
                        onClose();
                    }}>&times;</span>
                </div>
                <div className="drawer_body">
                    <FormBox>
                        <FormItemBox>
                            <div className="form_title_box">用户名称</div>
                            <InputX value={userName} onChange={(value) => setUserName(value)} />
                        </FormItemBox>
                        <FormItemBox>
                            <div className="form_title_box">管理员密码</div>
                            <InputX value={adminPassword} onChange={(value) => setAdminPassword(value)} />
                        </FormItemBox>
                        <FormItemBox>
                            <div className="form_title_box">密码</div>
                            <InputX value={password} onChange={(value) => setPassword(value)} />
                        </FormItemBox>
                        <FormItemBox>
                            <div className="form_title_box">确认密码</div>
                            <InputX value={passwordConfirm} onChange={(value) => setPasswordConfirm(value)} />
                        </FormItemBox>
                        <FormItemBox>
                            <div className="form_title_box">用户类型</div>
                            <SelectX selectTreeList={roleList} value={userType} onChange={(value) => handleChangeUserType(value)} />
                        </FormItemBox>
                        <FormItemBoxHeight>
                            <div className="form_title_box">分配权限</div>
                            <div className="tree_box">
                                <Tree treeData={treeData} selectIdArr={selectIdArr} setSelectIdArr={setSelectIdArr} />
                            </div>
                        </FormItemBoxHeight>

                    </FormBox>
                </div>
                <div className="drawer_footer">
                    <div style={{ marginRight: '2rem' }}>
                        <ButtonX type="info" onClick={() => {
                            handleCancel()
                            onClose();
                        }}>取消</ButtonX>
                    </div>
                    <ButtonX type='primary' onClick={() => handleSumber()}>确定</ButtonX>
                </div>
            </div>
        </DrawerAddChangeBox>
    }

export default DrawerAddChange;

